#!/usr/bin/python

import os, sys, time
import ConfigParser
from thrift import Thrift  
from thrift.transport import TSocket  
from thrift.transport import TTransport  
from thrift.protocol import TBinaryProtocol
from cassandra import Cassandra
from cassandra.ttypes import *
from protoBuff_decode import *
from google.appengine.datastore import entity_pb

DEBUG = True

if __name__ == '__main__':
    if len(sys.argv) < 2:
        print 'Usage: ' + sys.argv[0] + '  (key | data | get)'
        sys.exit(0)
    elif  sys.argv[1].lower() == 'get':
        if len(sys.argv) < 3:
            print 'Usage: ' + sys.argv[0] + '  get  your_key'
            sys.exit(0)
    
    db_operation_str = sys.argv[1]
    
    thrift_server_str = '128.111.55.223'
    thrift_port_int = 9160
    
    print 'Connecting to ' + thrift_server_str + ':' + str(thrift_port_int)
    transport = TTransport.TBufferedTransport(TSocket.TSocket(thrift_server_str, thrift_port_int))
    protocol = TBinaryProtocol.TBinaryProtocol(transport)
    client = Cassandra.Client(protocol)
    transport.open()
    print 'Connected!'
    
    keyspace = "Keyspace1"
    
    column_parent = ColumnParent(column_family="Standard1")
    
    keyslices = []
    predicate = SlicePredicate(column_names="")
    
    key_range = KeyRange("", "")
    
    keyslices = client.get_range_slices(
                keyspace, 
                column_parent, 
                predicate, 
                key_range, 
                ConsistencyLevel.ONE)
    
    userCount = 0
    logCount = 0
    if db_operation_str.lower() == 'key':
         
        #print '----------------------------------------------'
        for keyslice in keyslices:
	    if str(keyslice.key).startswith('JOURNAL_____actionlogtests___/actionlogtests/LogAction'):
		logCount += 1
	    if str(keyslice.key).startswith('JOURNAL_____actionlogtests___/actionlogtests/WebUser'):
                userCount += 1
            print 'key = ' + str(keyslice.key)
            print 'columns = ' + str(keyslice.columns)
            print '----------------------------------------------'
    print 'user count: ' + str(userCount)
    print 'log count: ' + str(logCount)
    
    slice_range = SliceRange(start="", finish="")
    predicate = SlicePredicate(slice_range=slice_range)
    key_counter = 0
    if db_operation_str.lower() == 'data':
        
        print '----------------------------------------------'
        for keyslice in keyslices:
            key_str = str(keyslice.key)
	        # get data from cassandra by key
            result_list = client.get_slice(keyspace,
                                          key_str,
                                          column_parent,
                                          predicate,
                                          ConsistencyLevel.ONE)
            print key_str
	    print 'Columns:'
            # print all columns found 
            for item in result_list:
                    value_name = item.column.name
                    value_str = item.column.value
		    print item
		    print "column name: " + value_name
		    print "column value: " + value_str
		    print '\n'
	    print '----------------------------------------------'
		    
	   
            if key_str.startswith('guestbook___'):
                for item in result_list:
                    result_dict = {}
                    if item.column.name == 'Encoded_Entity':
                        # decode Encoded_Entity
                        entity = entity_pb.EntityProto(item.column.value)
                        for property in entity.property_list() + entity.raw_property_list():
            
                            value_name = property.name()
                            
                            value_infos = property.value()
                            value_type, value_val = decode_value(value_infos)
                            ''' 
                            if value_type == "user":
                                if value_val.has_key('email'):
                                    result_dict[value_name] = str(value_val['email'])
                                else:
                                    result_dict[value_name] = ""
            #                    for k, v in value_val.items():
            #                        print "    " + str(k) + " : " + str(v) + "           " + str(type(v))
                            else:
			    '''
                            result_dict[value_name] = value_val
                        value_str = '\n            (decoded by protocol buffer)\n'
                        for k, v in result_dict.items():
                            value_str += '            ' + str(k) + ' : ' + str(v) + '\n'
                     
                    # print item
                    print '      value: ' + value_str
                print '----------------------------------------------'
    
	  
 
    if db_operation_str.lower() == 'get':
        key_str = sys.argv[2]
        print '----------------------------------------------'
        print 'key: ' + key_str
        print '----------------------------------------------'
        result_list = client.get_slice(keyspace,
                                          key_str,
                                          column_parent,
                                          predicate,
                                          ConsistencyLevel.ONE)
        
        print 'Columns:'
        # print all columns found 
        for item in result_list:
            
            print '      name : ' + str(item.column.name)
            print '      value: ' + str(item.column.value)
        print '----------------------------------------------'
    
    print 'done!'
   
    
    
    
    
    
        

